var winston = require('winston');
var fs = require('fs');
var path = require('path');
var archiver = require('archiver');

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var startTime = req.query.startTime || 0;
	var type = req.query.type || '';
	var action = req.query.action || '';
	var queryString;
	if(eventId){
		if(!type){
			queryString = 'SELECT photo_id, event_id, filename, is_portrait, timestamp FROM photo_list where event_id=' + eventId + ' and timestamp>' + startTime + ' and is_hidden=0 ORDER BY photo_id';
		}else{
			if(type === 'all'){
				queryString = 'SELECT photo_id, event_id, filename, is_portrait, is_hidden, timestamp FROM photo_list where event_id=' + eventId + ' ORDER BY photo_id';
			}else if(type === 'hide'){
				queryString = 'SELECT photo_id, event_id, filename, is_portrait, is_hidden, timestamp FROM photo_list where event_id=' + eventId + ' and is_hidden=1 ORDER BY photo_id';
			}else if(type === 'show'){
				queryString = 'SELECT photo_id, event_id, filename, is_portrait, is_hidden, timestamp FROM photo_list where event_id=' + eventId + ' and is_hidden=0 ORDER BY photo_id';
			}
		}
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}
			connection.query(queryString, function(err, rows){
				if(err){
					winston.error('DB query error: ' + err);
					res.status(500).send('DB query error: ' + err);
				}else{
					if(action == 'download' || action == 'downloadFrame' || action == 'downloadCrop'){
						if(rows.length > 0){
							var prefix = path.join(__dirname, '..', 'assets', eventId);
							var archivePrefix = path.join(__dirname, '..', 'public','archives');
							var archiveFile = action == 'download' ? archivePrefix + '/archive_' + eventId + '.zip'  : archivePrefix + '/archive_frame_' + eventId + '.zip';
							
							if(fs.existsSync(archiveFile)){
								fs.unlink(archiveFile, function(err){
									//console.log(err);
								});
							}
							
						
							var output = fs.createWriteStream(archiveFile);
							//生成archiver对象，打包类型为zip
							var zipArchiver = archiver('zip');
							//将打包对象与输出流关联
							zipArchiver.on('error', function(err){
								res.status(500).send({'error': err.message});
							});
							output.on('close', function(){
								res.send({msg: 'ok', name: path.basename(archiveFile)});
							});
							zipArchiver.pipe(output);
							rows.forEach(function(row, idx){
								var image = prefix + "/" + row.filename;
								var imageName = row.filename;
								if(action == 'downloadFrame'){
									image = image.replace(/\.([^\.]+)$/, "_c.$1");
									imageName = imageName.replace(/\.([^\.]+)$/, "_c.$1");
								}else if(action == 'downloadCrop'){
									image = image.replace(/\.([^\.]+)$/, "_crop.$1");
									imageName = imageName.replace(/\.([^\.]+)$/, "_crop.$1");
								}
								if(fs.existsSync(image)){
							  	zipArchiver.append(fs.createReadStream(image), {'name': imageName});
								}
							});

							zipArchiver.finalize();
						}else{
							res.end();
						}	
					}else{
						res.send(rows);
					}
				}
				connection.release();
			});
		});
	}else{
		winston.error('ROUT error, can not get eventId');
		res.status(500).send('ROUT error, can not get eventId')
	}
	
}